package com.china08.yxyapi.api.manage.stu.mystudy.homework.workreport;

import java.io.IOException;
import java.text.DecimalFormat;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import com.china08.yxyapi.entity.es.ElasticYxyYxyQuesResource;
import com.china08.yxyapi.entity.mg.homework.HomeworkTaskQues;
import com.china08.yxyapi.entity.mg.homework.HomeworkTaskQues.Article;
import com.china08.yxyapi.entity.mg.homework.HomeworkTaskReport;
import com.china08.yxyapi.entity.mg.homework.HomeworkTaskReportQues;
import com.china08.yxyapi.model.YxyApiReqModel;
import com.china08.yxyapi.model.YxyApiRespModel;
import com.china08.yxyapi.repository.es.ElasticYxyYxyQuesResourceRespository;
import com.china08.yxyapi.repository.mg.homework.HomeworkTaskQuesRepository;
import com.china08.yxyapi.repository.mg.homework.HomeworkTaskReportQuesRepository;
import com.china08.yxyapi.repository.mg.homework.HomeworkTaskReportRepository;
import com.china08.yxyapi.util.DateAndLocalDateConvertUtils;
import com.china08.yxyapi.util.DateUtils;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.JsonMappingException;

/**
 * 家长端作业系统 查看作业
 * 
 * @author yangyunying
 *
 */
// @Api(tags = { "v16", "查看作业" })
@CrossOrigin
@RestController
public class WorkReportCheckHomeFindController {

    @Autowired
    private HomeworkTaskReportQuesRepository homeworkTaskReportQuesRepository;

    @Autowired
    private HomeworkTaskReportRepository homeworkTaskReportRepository;

    @Autowired
    private ElasticYxyYxyQuesResourceRespository elasticYxyYxyQuesResourceRespository;

    @Autowired
    private HomeworkTaskQuesRepository homeworkTaskQuesRepository;

    /**
     * 查看家庭作业
     * 
     * @param request
     * @param response
     * @param req
     * @param respModel
     * @return
     * @throws IOException
     * @throws JsonMappingException
     * @throws JsonParseException
     */
    // @ApiOperation(value = "查看作业")
    @ResponseBody
    @RequestMapping(value = "/api_yw/manage/stu/mystudy/workreport/checkhome/srh", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public RespModel precess(@RequestBody ReqModel req, RespModel respModel)
            throws JsonParseException, JsonMappingException, IOException {
        long startQuery = System.currentTimeMillis();
        // 学生id
        String studentId = req.studentId;
        // 任务id
        String taskId = req.taskId;
        // 查看学生是否能答题
        List<HomeworkTaskQues> homeworkTaskQues3 = homeworkTaskQuesRepository.findByTaskId(taskId);
        Boolean ifNeedSumbit = true;
        try {
            ifNeedSumbit = homeworkTaskQues3.get(homeworkTaskQues3.size() - 1).getIfNeedSumbit();
        } catch (Exception e) {
            System.err.println("没有查到题");
        }
        // 判断是否只看错题
        Integer passed = req.passed == null ? 1 : req.passed;
        respModel = new RespModel();
        respModel.isShowAnswer = 0;
        respModel.ifNeedSumbit = ifNeedSumbit;
        // 查询作业标题 班级名 作业用时 正确率 评语
        HomeworkTaskReport homeworkTaskReport = homeworkTaskReportRepository.findByStudentIdAndTaskId(studentId,
                taskId);

        if (LocalDate.now().isBefore(DateAndLocalDateConvertUtils.asLocalDate(homeworkTaskReport.getPredictDate()))) {// 在截止时间之前
            if (homeworkTaskReport.getPublishAnswer() == 0 && (homeworkTaskReport.getStatusOfFinished() == 1
                    || homeworkTaskReport.getStatusOfFinished() == 2)) {
                respModel.isShowAnswer = 1;
            }
        } else {// 在截止时间之后 都需要显示
            respModel.isShowAnswer = 1;
        }
        // 获取当前时间
        Date currentDate = new Date();
        // 查询当前学生在当前任务下的截止时间
        Date predictDate = homeworkTaskReport.getPredictDate();
        if (predictDate.before(currentDate)) {
            respModel.booTime = 1;
        } else {
            respModel.booTime = 0;
        }
        // 发布答案解析：0--提交作业后，1--截止时间后
        respModel.publishAnswer = homeworkTaskReport.getPublishAnswer();
        // ##
        respModel.title = homeworkTaskReport.getTitle();
        respModel.studentNick = homeworkTaskReport.getStudentNick();
        respModel.className = homeworkTaskReport.getClassName();
        respModel.duration = DateUtils.getDurationDateByDurationCount(homeworkTaskReport.getDuration() * 1000);
        respModel.statusOfFinished = homeworkTaskReport.getStatusOfFinished();
        // 将double类型的数据保存到小数点的后两位
        DecimalFormat df = new DecimalFormat("######0.0");
        respModel.rightRate = Double.parseDouble(df.format(homeworkTaskReport.getRightRate()));
        respModel.evaluate = homeworkTaskReport.getEvaluate();
        System.out.println("查询作业标题 班级名 作业用时 正确率 评语 : " + (System.currentTimeMillis() - startQuery));
        // ###
        // 2. 根据题型查询作业信息===== questionType ====0--单选择题，1--多选择题，2--通知类
        List<HomeworkTaskReportQues> homeworkTaskReportQuesLst = null;

        if (passed == 0) {// 只看错题
            homeworkTaskReportQuesLst = homeworkTaskReportQuesRepository
                    .findByTaskIdAndStudentIdAndPassedAndMarkNotOrderByOrder(taskId, studentId, 0, 5);
        } else {
            homeworkTaskReportQuesLst = homeworkTaskReportQuesRepository.findByStudentIdAndTaskIdOrderByOrder(studentId,
                    taskId);
        }
        // 如果查出的预期提交状态时为null时
        System.out.println("查询学生已做作业 : " + (System.currentTimeMillis() - startQuery));
        // 每个任务下生成的试题
        if (homeworkTaskReportQuesLst == null || homeworkTaskReportQuesLst.size() == 0) {
            List<HomeworkTaskQues> homeworkTaskQuesLst = homeworkTaskQuesRepository
                    .findByTaskIdOrderByOrder(homeworkTaskReport.getTaskId());
            homeworkTaskReportQuesLst = new ArrayList<HomeworkTaskReportQues>();
            HomeworkTaskReportQues homeworkTaskReportQues = null;
            for (HomeworkTaskQues homeworkTaskQues : homeworkTaskQuesLst) {
                homeworkTaskReportQues = new HomeworkTaskReportQues();
                homeworkTaskReportQues.setQuestionType(homeworkTaskQues.getQuesType());
                homeworkTaskReportQues.setStudentId(homeworkTaskReport.getStudentId());
                homeworkTaskReportQues.setTaskId(homeworkTaskReport.getTaskId());
                homeworkTaskReportQues.setQuesId(homeworkTaskQues.getQuesId());
                homeworkTaskReportQues.setPassed(0);
                homeworkTaskReportQues.setDifficultyLevel(homeworkTaskQues.getDifficultyLevel());
                homeworkTaskReportQues.setKnowNameLst(homeworkTaskQues.getKnowName());
                homeworkTaskReportQuesLst.add(homeworkTaskReportQues);

                homeworkTaskQues = homeworkTaskQuesRepository.findByTaskIdAndQuesId(homeworkTaskReportQues.getTaskId(),
                        homeworkTaskReportQues.getQuesId());
            }
            homeworkTaskReportQuesRepository.save(homeworkTaskReportQuesLst);
        }
        System.out.println("每个任务下生成的试题 : " + (System.currentTimeMillis() - startQuery));
        // 试题
        List<HomeworkTaskReportQuesModel> homeworkTaskReportQuesModelLst = new ArrayList<HomeworkTaskReportQuesModel>();
        // 通知
        List<HomeworkTaskReportQuesModel> noticeHomeworkTaskReportQuesModelLst = new ArrayList<HomeworkTaskReportQuesModel>();
        HomeworkTaskReportQuesModel noticeHomeworkTaskReportQuesModel = null;
        HomeworkTaskReportQuesModel homeworkTaskReportQuesModel = null;
        ElasticYxyYxyQuesResource elasticYxyYxyQuesResource = null;
        // 单选试题值
        Integer singleCount = 0;
        // 多选试题值
        Integer moreCount = 0;
        // 填空题
        Integer fillBlanksCount = 0;
        // 简答题
        Integer simpleCount = 0;
        // 通知试题值
        Integer noticeCount = 0;
        HomeworkTaskQues homeworkTaskQues = null;
        System.out.println("开始组装返回试题的实体 begin: " + (System.currentTimeMillis() - startQuery));
        for (HomeworkTaskReportQues homeworkTaskReportQues : homeworkTaskReportQuesLst) {
            if ("0".equals(homeworkTaskReportQues.getQuestionType())
                    || "1".equals(homeworkTaskReportQues.getQuestionType())
                    || "3".equals(homeworkTaskReportQues.getQuestionType())
                    || "4".equals(homeworkTaskReportQues.getQuestionType())) {
                homeworkTaskReportQuesModel = new HomeworkTaskReportQuesModel();
                if ("0".equals(homeworkTaskReportQues.getQuestionType())) {
                    singleCount += 1;
                    homeworkTaskReportQuesModel.count = singleCount;
                }
                if ("1".equals(homeworkTaskReportQues.getQuestionType())) {
                    moreCount += 1;
                    homeworkTaskReportQuesModel.count2 = moreCount;
                }
                if (homeworkTaskReportQues.getQuestionType().equals("3")) {
                    fillBlanksCount += 1;
                    homeworkTaskReportQuesModel.count3 = moreCount;
                }
                if (homeworkTaskReportQues.getQuestionType().equals("4")) {
                    simpleCount += 1;
                    homeworkTaskReportQuesModel.count4 = moreCount;
                }
                homeworkTaskReportQuesModel.questionType = homeworkTaskReportQues.getQuestionType();
                homeworkTaskReportQuesModel.answerText = homeworkTaskReportQues.getAnswerText();
                homeworkTaskReportQuesModel.answerOfMy = homeworkTaskReportQues.getAnswerOfMy();
                homeworkTaskReportQuesModel.answerOfMyImgs = homeworkTaskReportQues.getAnswerImgs();
                homeworkTaskReportQuesModel.answerOfQues = homeworkTaskReportQues.getAnswerOfQues();
                homeworkTaskReportQuesModel.passed = homeworkTaskReportQues.getPassed();
                homeworkTaskReportQuesModel.mark = homeworkTaskReportQues.getMark();
                homeworkTaskReportQuesModel.order = homeworkTaskReportQues.getOrder();
                homeworkTaskReportQuesModel.quesId = homeworkTaskReportQues.getQuesId();
                homeworkTaskReportQuesModel.notifyPassed = homeworkTaskReportQues.getNotifyPassed();
                homeworkTaskReportQuesModel.difficultyLevel = homeworkTaskReportQues.getDifficultyLevel();
                homeworkTaskReportQuesModel.knowNameLst = homeworkTaskReportQues.getKnowNameLst();
                System.out.println("开始查询试题 begin : " + (System.currentTimeMillis() - startQuery));
                elasticYxyYxyQuesResource = elasticYxyYxyQuesResourceRespository
                        .findById(homeworkTaskReportQues.getQuesId());
                System.out.println("开始查询试题 end : " + (System.currentTimeMillis() - startQuery));
                homeworkTaskReportQuesModel.quesBody = elasticYxyYxyQuesResource;
                System.out.println("解析试题 end : " + (System.currentTimeMillis() - startQuery));
                homeworkTaskReportQuesModelLst.add(homeworkTaskReportQuesModel);
            } else {
                noticeCount += 1;
                noticeHomeworkTaskReportQuesModel = new HomeworkTaskReportQuesModel();
                noticeHomeworkTaskReportQuesModel.questionType = homeworkTaskReportQues.getQuestionType();
                noticeHomeworkTaskReportQuesModel.answerText = homeworkTaskReportQues.getAnswerText();
                noticeHomeworkTaskReportQuesModel.answerOfMyImgs = homeworkTaskReportQues.getAnswerImgs();
                noticeHomeworkTaskReportQuesModel.answerOfMy = null;
                noticeHomeworkTaskReportQuesModel.answerOfQues = null;
                noticeHomeworkTaskReportQuesModel.passed = homeworkTaskReportQues.getPassed();
                noticeHomeworkTaskReportQuesModel.order = homeworkTaskReportQues.getOrder();
                noticeHomeworkTaskReportQuesModel.notifyPassed = homeworkTaskReportQues.getNotifyPassed();
                noticeHomeworkTaskReportQuesModel.title = homeworkTaskReportQues.getTitle();
                noticeHomeworkTaskReportQuesModel.quesBody = null;
                homeworkTaskQues = homeworkTaskQuesRepository.findByTaskIdAndQuesId(homeworkTaskReportQues.getTaskId(),
                        homeworkTaskReportQues.getQuesId());
                if (homeworkTaskQues != null) {
                    noticeHomeworkTaskReportQuesModel.quesContent = homeworkTaskQues.getQuesContent();// 老师布置作业编辑的内容
                    noticeHomeworkTaskReportQuesModel.quesImage = homeworkTaskQues.getQuesImage();// 通知试题图片
                    noticeHomeworkTaskReportQuesModel.quesArticle = homeworkTaskQues.getQuesArticle();// 文档地址文档名称
                    if (noticeHomeworkTaskReportQuesModel.quesArticle != null
                            && noticeHomeworkTaskReportQuesModel.quesArticle.size() > 0) {
                        for (Article article : noticeHomeworkTaskReportQuesModel.quesArticle) {
                            if (StringUtils.isBlank(article.getArticle_name())) {
                                article.setArticle_name("未命名文件");
                            }
                        }
                    }
                }
                noticeHomeworkTaskReportQuesModelLst.add(noticeHomeworkTaskReportQuesModel);
            }
        }
        respModel.homeworkTaskReportQuesLst = homeworkTaskReportQuesModelLst;

        // 如果逾期没提交，通知类试题学生没有回答也没有提交的情况下，为保证能在查看作业页面能够看到通知类的作业
        if (noticeHomeworkTaskReportQuesModelLst == null || noticeHomeworkTaskReportQuesModelLst.size() == 0) {
            List<HomeworkTaskQues> homeworkTaskQuesLst = homeworkTaskQuesRepository
                    .findByTaskIdOrderByOrder(homeworkTaskReport.getTaskId());
            for (HomeworkTaskQues homeworkTaskQues2 : homeworkTaskQuesLst) {
                noticeHomeworkTaskReportQuesModel = new HomeworkTaskReportQuesModel();
                noticeHomeworkTaskReportQuesModel.questionType = homeworkTaskQues2.getQuesType();
                noticeHomeworkTaskReportQuesModel.answerText = null;
                noticeHomeworkTaskReportQuesModel.answerOfMyImgs = null;
                noticeHomeworkTaskReportQuesModel.answerOfMy = null;
                noticeHomeworkTaskReportQuesModel.answerOfQues = null;
                noticeHomeworkTaskReportQuesModel.passed = null;
                noticeHomeworkTaskReportQuesModel.order = homeworkTaskQues2.getOrder();
                noticeHomeworkTaskReportQuesModel.notifyPassed = null;
                noticeHomeworkTaskReportQuesModel.title = homeworkTaskQues2.getTitle();
                noticeHomeworkTaskReportQuesModel.quesBody = null;
                homeworkTaskQues = homeworkTaskQuesRepository.findByTaskIdAndQuesId(homeworkTaskQues2.getTaskId(),
                        homeworkTaskQues2.getQuesId());
                if (homeworkTaskQues != null) {
                    noticeHomeworkTaskReportQuesModel.quesContent = homeworkTaskQues.getQuesContent();// 老师布置作业编辑的内容
                    noticeHomeworkTaskReportQuesModel.quesImage = homeworkTaskQues.getQuesImage();// 通知试题图片
                    noticeHomeworkTaskReportQuesModel.quesArticle = homeworkTaskQues.getQuesArticle();// 文档地址文档名称
                    if (noticeHomeworkTaskReportQuesModel.quesArticle != null
                            && noticeHomeworkTaskReportQuesModel.quesArticle.size() > 0) {
                        for (Article article : noticeHomeworkTaskReportQuesModel.quesArticle) {
                            if (StringUtils.isBlank(article.getArticle_name())) {
                                article.setArticle_name("未命名文件");
                            }
                        }
                    }
                }
                noticeHomeworkTaskReportQuesModelLst.add(noticeHomeworkTaskReportQuesModel);
            }
        }
        respModel.noticeHomeworkTaskReportQuesLst = noticeHomeworkTaskReportQuesModelLst;
        // 查询单选题和多选题和通知题的数量
        respModel.singleCount = singleCount;
        respModel.moreCount = moreCount;
        respModel.fillBlanksCount = fillBlanksCount;
        respModel.simpleCount = simpleCount;
        respModel.noticeCount = noticeCount;
        System.out.println("开始组装返回试题的实体  end : " + (System.currentTimeMillis() - startQuery));
        return respModel;
    }

    protected static class ReqModel extends YxyApiReqModel {
        // 任务id
        public String taskId;
        // 学生id
        public String studentId;
        // 判断是否只看错题
        public Integer passed;
    }

    /**
     * 试题每道题详细信息
     */
    public class HomeworkTaskReportQuesModel {
        // 题目的类型
        public String questionType;
        // 通知作业的标题
        public String title;
        // 通知类试题的答案
        public String answerText;
        // 我的回答
        public String answerOfMy;
        // 我的回答 - IMG
        public List<String> answerOfMyImgs;
        // 单选多选正确答案
        public String answerOfQues;
        // 试题类作业是否正确 0-错误 , 1-正确 ,2-半对 20% ,3-半对 30% ,4-半对 80%
        public Integer passed;
        // 通知类作业是否正确 1-优, 2-良, 3-中, 4-差
        public Integer notifyPassed;
        // 主观题得分
        public Integer mark = null;
        // 题的序号
        public Integer order;
        // 题的详细信息
        public Object quesBody;
        // 题id
        public String quesId;
        // 通知类作业，上传的图片Url
        public List<String> quesImage;
        // 通知类作业，上传的文档,需要存储文档地址，文档的名称
        public List<Article> quesArticle;
        // 通知类作业 老师布置作业编辑的内容
        public String quesContent;
        // 单选题号模拟
        public Integer count = 0;
        // 多选题号模拟
        public Integer count2 = 0;
        // 填空
        public Integer count3 = 0;
        // 简答
        public Integer count4 = 0;
        // 题的难易程度
        public Integer difficultyLevel;
        // 知识点:Name
        public List<String> knowNameLst;

    }

    protected static class RespModel extends YxyApiRespModel {
        // 查看作业页面的标题
        public String title;
        // 所在班级的名称
        public String className;
        // 学生名称
        public String studentNick;
        // 作业用时
        public String duration;
        // 正确率
        public Double rightRate;
        // 教师评语
        public String evaluate;
        // 通知题
        public List<HomeworkTaskReportQuesModel> noticeHomeworkTaskReportQuesLst;
        // 试题
        public List<HomeworkTaskReportQuesModel> homeworkTaskReportQuesLst;
        // 单选题的数量
        public Integer singleCount;
        // 多选题的数量
        public Integer moreCount;
        // 通知试题的数量
        public Integer noticeCount;
        // 填空题
        public Integer fillBlanksCount;
        // 简答题
        public Integer simpleCount;
        // 判断当前时间是否超过截止时间(0:未超过、1：已超过)
        public Integer booTime;
        // 作业完成情况:-1-逾期未提交,0-未做,1-完成 ,2-已批阅,3-答题中
        public Integer statusOfFinished;
        // 是否能查看答案 0 是不显示 1 是显示
        public Integer isShowAnswer;
        // 发布答案解析：0--提交作业后，1--截止时间后
        public Integer publishAnswer;
        // 通知类作业是否需要学生在线提交true需要,false不需要
        public Boolean ifNeedSumbit;
    }
}
